package ltd.starriddle.smart4j.chapter2.controller;

import ltd.starriddle.smart4j.chapter2.service.CustomerService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 创建客户
 *
 * @author chen
 */
@WebServlet("/customer_create")
public class CustomerCreateServlet extends HttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerCreateServlet.class);

    private CustomerService customerService;

    @Override
    public void init() throws ServletException {
        customerService = new CustomerService();
    }

    /**
     * 进入 创建客户 界面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LOGGER.info("创建客户");

        req.getRequestDispatcher("/WEB-INF/view/customer_create.jsp").forward(req, resp);
    }

    /**
     * 处理 创建客户 请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = Optional.of(req.getParameter("name")).orElse("").trim();
        String contact = Optional.of(req.getParameter("contact")).orElse("").trim();
        String phone =  Optional.of(req.getParameter("phone")).orElse("").trim();
        String email =  Optional.of(req.getParameter("email")).orElse("").trim();
        String remark =  Optional.of(req.getParameter("remark")).orElse("").trim();
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("name", name);
        fieldMap.put("contact", contact);
        fieldMap.put("phone", phone);
        fieldMap.put("email", email);
        fieldMap.put("remark", remark);
        LOGGER.info("req 创建客户 fieldMap={}", fieldMap);

        boolean result = false;
        if (StringUtils.isNoneBlank(name, contact)) {
            result = customerService.createCustomer(fieldMap);
        }
        req.setAttribute("result", result);
        LOGGER.info("resp 创建客户 result={}", result);

        req.getRequestDispatcher("/WEB-INF/view/customer_create.jsp").forward(req, resp);
    }
}
